package com.sibrary.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.Context;

import com.sibrary.booxoo.download.BooxooDownloadItem;

public class DomUtils {

	private final static String mFilename = "x.xml";

	/**
	 * 创建xml
	 */
	public static void createXml(BooxooDownloadItem item) {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();
			Document doc = dbBuilder.newDocument();

			// 创建xml根元素
			Element root = doc.createElement("Downloads");
			doc.appendChild(root);

			// 添加项
			Element DownloadItem = doc.createElement("Download");
			DownloadItem.setAttribute("Url", item.getUrl());
			DownloadItem.setAttribute("Filename", item.getFilename());
			DownloadItem.setAttribute("DownloadCancel",
					item.getDownloadCancel());
			root.appendChild(DownloadItem);

			saveXml(doc, mFilename);
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 解析xml文件，返回对象集合
	 */
	public static List<BooxooDownloadItem> parseXml() {
		List<BooxooDownloadItem> Downloads = new ArrayList<BooxooDownloadItem>();

		Document doc = getDocFromXml(mFilename);
		Element root = doc.getDocumentElement();
		NodeList nodes = root.getElementsByTagName("Download");

		for (int i = 0; i < nodes.getLength(); i++) {
			Element download = (Element) nodes.item(i);
			BooxooDownloadItem item = new BooxooDownloadItem();

			item.setUrl(download.getAttribute("Url"));
			item.setFilename(download.getAttribute("Filename"));
			item.setDownloadCancel(download.getAttribute("DownloadCancel"));
			Downloads.add(item);
		}
		return Downloads;
	}

	/**
	 * 向已存在的xml文件中插入元素
	 **/
	public static void insertItemInXml(BooxooDownloadItem item) {
		Document doc = getDocFromXml(mFilename);
		Element root = doc.getDocumentElement();

		// 添加项
		Element DownloadItem = doc.createElement("Download");
		DownloadItem.setAttribute("Url", item.getUrl());
		DownloadItem.setAttribute("Filename", item.getFilename());
		DownloadItem.setAttribute("DownloadCancel", item.getDownloadCancel());
		root.appendChild(DownloadItem);
		saveXml(doc, mFilename);
	}

	/**
	 * 修改元素
	 **/
	public static void alterItemInXml(BooxooDownloadItem item) {
		Document doc = getDocFromXml(mFilename);
		Element root = doc.getDocumentElement();
		NodeList nodes = root.getElementsByTagName("Download");

		for (int i = 0; i < nodes.getLength(); i++) {
			Element elem = (Element) nodes.item(i);
			if (item.getUrl().equals(elem.getAttribute("Url"))
					&& item.getFilename().equals(elem.getAttribute("Filename"))) {
				elem.setAttribute("DownloadCancel", item.getDownloadCancel());
				break;
			}
		}
		saveXml(doc, mFilename);
	}

	/**
	 * 删除节点
	 */
	public static void deleteItemInXml(BooxooDownloadItem item) {
		Document doc = getDocFromXml(mFilename);
		Element root = doc.getDocumentElement();
		NodeList nodes = root.getElementsByTagName("Download");
		for (int i = 0; i < nodes.getLength(); i++) {
			Element elem = (Element) nodes.item(i);

			if (item.getUrl().equals(elem.getAttribute("Url"))
					&& item.getFilename().equals(elem.getAttribute("Filename"))) {
				root.removeChild(elem);
				break;
			}
		}
		saveXml(doc, mFilename);
	}

	/**
	 * 获取doc
	 */
	private static Document getDocFromXml(final String filename) {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder dbBuilder;
			dbBuilder = dbFactory.newDocumentBuilder();
			Document doc = dbBuilder.parse(Constants.mContext
					.openFileInput(filename));
			return doc;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * This method writes a DOM document to a file
	 */
	private static void saveXml(Document doc, final String filename) {
		try {
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource domSource = new DOMSource(doc);
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			FileOutputStream fileOutputStream = Constants.mContext
					.openFileOutput(filename, Context.MODE_PRIVATE);
			PrintWriter printWriter = new PrintWriter(fileOutputStream);
			StreamResult result = new StreamResult(printWriter);
			transformer.transform(domSource, result);
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 判断xml文件是否存在
	 */
	public static boolean isExists() {
		FileInputStream fileInputStream;
		try {
			fileInputStream = Constants.mContext.openFileInput(mFilename);
			int fileSize = fileInputStream.available(); // 文件大小
			if (fileSize <= 0) {
				return false;
			} else {
				return true;
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查找是否有相同项
	 */
	public static boolean hasSameItem(BooxooDownloadItem item) {
		Document doc = getDocFromXml(mFilename);
		Element root = doc.getDocumentElement();

		NodeList nodes = root.getElementsByTagName("Download");

		for (int i = 0; i < nodes.getLength(); i++) {
			Element elem = (Element) nodes.item(i);
			if (item.getUrl().equals(elem.getAttribute("Url"))
					&& item.getFilename().equals(elem.getAttribute("Filename"))) {
				item.setDownloadCancel(elem.getAttribute("DownloadCancel"));
				return true;
			}
		}
		return false;
	}
}
